"""
统计微信好友信息，包括:
    1. 性别比例
    2. 地域分布
    3. 签名信息
@author: yooongchun@foxmail.com
@time: 2021.12.30
"""
from urllib.parse import quote_plus
import webbrowser

import itchat
import requests
import pyecharts.options as opts
from pyecharts.charts import Pie
from pyecharts.globals import ThemeType


def get_qrcode():
    """获取二维码"""
    itchat.auto_login(hotReload=True)
    
    itchat.send('Hello, filehelper', toUserName='filehelper')
    friends = itchat.get_friends(update=True)


def get_lati_longitude(address):
    """根据地名获得经纬度信息"""
    api = 'http://api.map.baidu.com/geocoder/v2/'
    output = 'json'
    ak = 'x2ZTlRkWM2FYoQbvGOufPnFK3Fx4vFR1'
    url = f'{api}?address={quote_plus(address)}&output={output}&ak={ak}'
    response = requests.get(url, timeout=5)
    res = response.json()
    return res


def stats_frinds_info(users):
    """统计好友信息"""
    result = {'male': 0, 'female': 0, 'other': 0, 'address': {}, 'signature': [], 'stars': 0}
    for user in users:
        # 性别
        if user['Sex'] == 1:
            result['male'] += 1
        elif user['Sex'] == 2:
            result['female'] += 1
        else:
            result['other'] += 1
        # 标星
        result['stars'] += user['StarFriend'] == 1
        # 城市
        addr = user['Province'] + user['City']
        result['address'][addr] = result['address'].get(addr, 0) + 1
        # 签名数据
        result['signature'].append(user['Signature'])
    return result


def get_posi(result):
    """批量获取经纬度信息"""
    for addr in result['address']:
        if addr:
            try:
                resp = get_lati_longitude(addr)
                lng = resp['result']['location']['lng']
                lat = resp['result']['location']['lat']
                result['address'][addr] = [lng,lat, result['address'][addr]]
            except Exception as e:
                print(addr, e)


def stats_sex_rate(result):
    """统计性别比例"""

    male = result['male']
    female = result['female']
    other = result['other']
    stars = result['stars']

    inner_x_data = ["有性别", "无性别"]
    inner_y_data = [male+female, other]
    inner_data_pair = [list(z) for z in zip(inner_x_data, inner_y_data)]

    outer_x_data = ["男性", "女性", "其他"]
    outer_y_data = [male, female, other]
    if stars:
        outer_x_data.append("星标")
        outer_y_data.append(stars)
    outer_data_pair = [list(z) for z in zip(outer_x_data, outer_y_data)]

    pie = (Pie(init_opts=opts.InitOpts(width="800px", height="600px", theme=ThemeType.WHITE))
        .add(series_name="性别数据",
            data_pair=inner_data_pair,
            radius=[0, "30%"],
            label_opts=opts.LabelOpts(position="inner"))
            .add(series_name="性别数据",
                radius=["40%", "55%"],
                data_pair=outer_data_pair,
                label_opts=opts.LabelOpts(
                    position="outside",
                    formatter="{a|{a}}{abg|}\n{hr|}\n {b|{b}: }{c}  {per|{d}%}  ",
                    background_color="#eee",
                    border_color="#aaa",
                    border_width=1,
                    border_radius=4,
                    rich={
                        "a": {"color": "#999", "lineHeight": 22, "align": "center"},
                        "abg": {
                            "backgroundColor": "#e3e3e3",
                            "width": "100%",
                            "align": "right",
                            "height": 22,
                            "borderRadius": [4, 4, 0, 0],
                        },
                        "hr": {
                            "borderColor": "#aaa",
                            "width": "100%",
                            "borderWidth": 0.5,
                            "height": 0,
                        },
                        "b": {"fontSize": 16, "lineHeight": 33},
                        "per": {
                            "color": "#eee",
                            "backgroundColor": "#334455",
                            "padding": [2, 4],
                            "borderRadius": 2,
                        },
                },
            ),
        )
        .set_global_opts(legend_opts=opts.LegendOpts(pos_left="left", orient="vertical"))
        .set_series_opts(tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)")))

    pie.render_notebook()


def stats_addr(result):
    """统计地域分布"""
    addr_strs = ''
    posi_strs = ''
    for city, vals in result['address'].items():
        if isinstance(vals, list) and len(vals) == 3:
            json_str = '{name: "%s", value: %s}'%(city, vals[2])
            addr_strs += '\n' + json_str + ','
            json_str = f'{city.replace(" ", "")}: {[round(vals[0],2), round(vals[1], 2)]}'
            posi_strs += '\n' + json_str + ','

    with open('template.html', 'r', encoding='utf-8') as fp:
        html_text = fp.read()

    html_text = html_text.replace("NEED_ADDR_DATA", addr_strs)
    html_text = html_text.replace("NEED_POSI_DATA", posi_strs)
    with open("好友地域分布图.html", 'w', encoding='utf-8') as fp:
        fp.write(html_text)

    webbrowser.open('好友地域分布图.html', new=0, autoraise=True)